package com.atguigu.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.annotation.JSONPOJOBuilder;
import com.atguigu.common.feignTo.es.SkuEsModel;
import com.atguigu.gulimall.search.config.GulimallElasticSearchConfig;
import com.atguigu.gulimall.search.constant.EsConstant;
import com.atguigu.gulimall.search.service.ProductSaveService;
import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonFormatVisitable;
import com.sun.org.apache.bcel.internal.generic.RETURN;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service("productSaveService")
public class ProductSaveServiceImpl implements ProductSaveService {

    @Autowired
    private RestHighLevelClient client;

    @Override
    public Boolean productStatusUp(List<SkuEsModel> esModels) throws IOException {

        BulkRequest bulkRequest = new BulkRequest();
        esModels.stream().forEach(n -> {
            IndexRequest indexRequest = new IndexRequest();
            indexRequest.id(n.getSkuId().toString())
                        .source(JSON.toJSONString(n), XContentType.JSON)
                        .index(EsConstant.PRODUCT_INDEX);
            bulkRequest.add(indexRequest);
        });

        BulkResponse bulk = client.bulk(bulkRequest, GulimallElasticSearchConfig.COMMON_OPTIONS);

        log.info("商品上架成功：：：{}", Arrays.stream(bulk.getItems()).map(item -> item.getId()).collect(Collectors.toList()));
        return bulk.hasFailures();
    }
}
